package fantasy;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Properties;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthSigner;

@SuppressWarnings("unused")
public class GOAuthStartServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8270802349889295588L;
	
	protected void service(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
				
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null) {
        	
    		String baseurl = "http://dhpollack944.appspot.com";
    		String GOOGLE_CONSUMER_KEY = "dhpollack944.appspot.com";
    		String GOOGLE_CONSUMER_SECRET = "5sLdLvnBuYa+fpcWdzie9ndr";
    		
    		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
    		oauthParameters.setOAuthConsumerKey(GOOGLE_CONSUMER_KEY);
    		oauthParameters.setOAuthConsumerSecret(GOOGLE_CONSUMER_SECRET);
    		oauthParameters.setScope("https://docs.google.com/feeds/ https://spreadsheets.google.com/feeds/");

    		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());

    	    try {
    			oauthHelper.getUnauthorizedRequestToken(oauthParameters);

    			String oauth_token_secret = oauthParameters.getOAuthTokenSecret();
    			StringBuilder stringBuilder = new StringBuilder();
    			stringBuilder.append(baseurl);
    			stringBuilder.append("/goauthtwo");
    			stringBuilder.append("?oauth_token_secret=");
    			stringBuilder.append(URLEncoder.encode(oauth_token_secret,"UTF-8"));
    			oauthParameters.setOAuthCallback(stringBuilder.toString());

    			String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);

    			log("OAuth Token Secret: " + oauth_token_secret);
    			log("Request URL: " + requestUrl);
    			
    			resp.sendRedirect(requestUrl);
    			

    		} catch (OAuthException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
	}
}
